/**
  Basic sample TCP/IP Server programme in C
  Socket family -> AF_INET
  socket_type   -> SOCK_STREAM
  
  This program accepts connection from clientser and prints message.
  Change the _PORT and _ADDR values to point to your server.

  Skelton of Server program
    socket()
    bind()
    listen()
    accept()
    read()
    write()
    close()

**/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define _PORT 12345
#define _ADDRESS "127.0.0.1"

int main()
{
  struct sockaddr_in addr;
  int sock,conn;
  int n=0;
  char buffer[128];
  char *msg="Hello, I am server";
  
  /* Get socket descriptor */
  sock=socket(AF_INET,SOCK_STREAM,0);
  if( sock == -1 )
  {
    perror("Error in creating socket");
    return 1;
  }
  
  memset(&addr,0,sizeof(struct sockaddr_in));
  addr.sin_family=AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port=htons(_PORT);
  
  bind(sock,(struct sockaddr*)&addr,sizeof(struct sockaddr));
    
  listen(sock,2);
  
  conn=accept(sock,(struct sockaddr*)NULL,NULL);
  
  printf("Connected\n");
  
  memset(buffer,0,sizeof(buffer));
  n=read(conn,buffer,sizeof(buffer)-1);
  if( n>0 ){
    buffer[n]='\0';
    printf("Number of bytes read = '%d' \n",n);
    printf("msg received = '%s'\n",buffer);
  }
  
  n=write(conn,msg,strlen(msg));
  if( n>0 ){
    printf("Bytes written = '%d'\n",n);
  }
  
  /* Close socket */
  close(sock);
  close(conn);
  
}
